package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Poi;
import cn.wolfcode.luowowo.article.mapper.DestinationMapper;
import cn.wolfcode.luowowo.article.mapper.PoiMapper;
import cn.wolfcode.luowowo.article.service.IPoiService;
import cn.wolfcode.luowowo.article.vo.PoiDestVo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PoiServiceImpl implements IPoiService {

    @Autowired
    private PoiMapper poiMapper;

    @Autowired
    private DestinationMapper destMapper;

    public Poi get(Long id) {
        Poi poi = poiMapper.selectByPrimaryKey(id);
        poi.setChildren(poiMapper.selectByParent(id));
        return poi;
    }

    public List<Poi> queryTop5ByParent(Long parentId) {
        List<Poi> pois = poiMapper.selectTop5ByParent(parentId);
        for (Poi poi : pois) {
            List<Poi> children = poiMapper.selectByParent(poi.getId());
            poi.setChildren(children);
        }
        return pois;
    }

    public void updateReplynum(Long poiId, int num) {
        poiMapper.updateReplynum(poiId, num);
    }

    public Poi getByDestId(Long destId) {
        return poiMapper.selectByDestId(destId);
    }

    public List<Poi> queryTop3ByParentId(Long destId) {
        return poiMapper.queryTop3ByParentId(destId);
    }

    public List<PoiDestVo> queryPoisAndDest(List<Long> pids) {
        if (pids == null || pids.size()<=0){
            return null;
        }
        List<Poi> pois = poiMapper.selectByIds(pids);
        List<PoiDestVo> poiDestVos = new ArrayList();

        Map<String, List<Poi>> map = new HashMap<>();
        // 遍历pois
        for (Poi poi : pois) {
            Destination dest = destMapper.selectByPrimaryKey(poi.getDest().getId());
            String key = dest.getId().toString();
            if (map.containsKey(key)){
                List<Poi> ps = map.get(key);
                ps.add(poi);
                map.put(key, ps);
            } else {
                List<Poi> ps  = new ArrayList<>();
                ps.add(poi);
                map.put(key, ps);
            }
        }

        for (String key : map.keySet()) {
            PoiDestVo poiDestVo = new PoiDestVo();
            poiDestVo.setDest(destMapper.selectByPrimaryKey(Long.valueOf(key)));
            poiDestVo.setPois(map.get(key));
            poiDestVos.add(poiDestVo);
        }
        return poiDestVos;
    }

}
